package com.updalod.util;

import com.updalod.properties.MinIoProperties;
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;
import java.util.UUID;

/**
 * @program: minio
 * @description:
 * @author: WuChengXing
 * @create: 2020-07-16 21:08
 **/
@Component
@EnableConfigurationProperties(MinIoProperties.class)
public class MinIoUtil {

    @Autowired
    private MinIoProperties minIoProperties;

    public static String BUCKET = "gyt";

    public String fileUpload(MultipartFile file, String dir) {
        if (file.isEmpty() || file.getSize() == 0) {
            return "文件为空";
        }
        try {
            //连接
            MinioClient minioClient = new MinioClient(minIoProperties.getEndpoint(), minIoProperties.getAccessKey(), minIoProperties.getSecretKey());
            //是否存在名为“test”的bucket
            if (!minioClient.bucketExists(BUCKET)) {
                minioClient.makeBucket(BUCKET);
            }
            String fileName = file.getOriginalFilename();
            String newName = dir + "/" + LocalDate.now() + "/" + UUID.randomUUID().toString().replaceAll("-", "")
                    + "-" + BUCKET + "-" + fileName;
            //新的名称，pic会是bucket下的文件夹
            //获取file的inputStream
            InputStream inputStream = file.getInputStream();
            // 上传
            minioClient.putObject(BUCKET, newName, inputStream, "application/octet-stream");
            inputStream.close();
            //文件访问路径
            String url = minioClient.getObjectUrl(BUCKET, newName);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传失败";
    }
}
